package com.rfid.analysis;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;

/**
 * @author Administrator
 * @date 2020/9/16
 * 帧类型
 */
public class HandlerType extends Handler {

    private final List<byte[]> mTypeList;

    public HandlerType(@NonNull List<byte[]> typeList) {
        mTypeList = typeList;
    }

    @Override
    public void handleRequest(Message request) {
        request.setCurrentNodeHandler(this);
        ByteBuffer byteBuffer = request.getBuffer();
        if (byteBuffer.position() + getLength() <= byteBuffer.limit()) {
            for (byte[] bytes : mTypeList) {
                byteBuffer.mark();
                byte[] read = new byte[bytes.length];
                byteBuffer.get(read);
                if (Arrays.equals(bytes, read)) {
                    //读取成功
                    request.addData(read);
                    if (getNext() != null) {
                        getNext().handleRequest(request);
                    }
                    return;
                } else {
                    byteBuffer.reset();
                }
            }
            //错误数据从头开始解析
            request.getFirstHandler().handleRequest(request);
        } else {
            byteBuffer.compact();
        }
    }



    private int getLength() {
        return 1;
    }

}